package com.common.utils;

import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author liuxuhuang
 * @date 2023年03月31日 20:55
 */
@Component
public class ImageUtil {
    /**
     * 将bufferedImage转为Base64
     *
     * @param image
     * @return
     * @throws IOException
     */
    public String convertBufferedImageToBase64(BufferedImage image) throws IOException {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", stream);
        byte[] bytes = stream.toByteArray();
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encodeBuffer(bytes).trim().replaceAll("\n", "").replaceAll("\r", "");
    }
}
